package com.v3admin.system.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.v3admin.common.enums.SystemConst;
import com.v3admin.common.enums.UserStatusEnum;
import com.v3admin.common.exception.BusinessException;
import com.v3admin.system.config.UserPasswordRsaConfig;
import com.v3admin.system.domain.SystemUser;
import com.v3admin.system.domain.vo.SystemUserVO;
import com.v3admin.system.domain.vo.UserLoginVO;
import com.v3admin.system.domain.vo.UserTokenVO;
import com.v3admin.system.service.SystemUserService;
import com.v3admin.system.service.UserLoginService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户登录
 *
 * @author Junpeng.Li
 * @date 2023-12-13 17:35
 */
@Service
@AllArgsConstructor
public class UserLoginServiceImpl implements UserLoginService {

    private final SystemUserService userService;

    private final UserPasswordRsaConfig rsaConfig;

    @Override
    public UserTokenVO login(UserLoginVO loginInfo) {
        String password;
        try {
            // 解密前端传入的密文密码
            password = SaSecureUtil.rsaDecryptByPrivate(rsaConfig.getPrivateKey(), loginInfo.getPassword());
        } catch (Exception e) {
            throw new BusinessException("用户名或密码错误");
        }

        // 校验密码
        SystemUser user = userService.getByUsername(loginInfo.getUsername());
        if (null == user || !this.comparePassword(user.getPassword(), password)) {
            throw new BusinessException("用户名或密码错误");
        }

        // 账号冻结处理
        if (user.getStatus() == UserStatusEnum.freeze) {
            // 永久冻结
            if (null == user.getFreezeEndTime()) {
                throw new BusinessException(
                        "您的账号已被永久冻结，无法继续使用本系统。冻结开始时间：{} ",
                        DateUtil.formatDateTime(user.getFreezeStartTime()));
            }
            // 有期限冻结
            throw new BusinessException(
                    "您的账号已被冻结，暂时无法登录系统。冻结时间自 {} 起至 {} 止",
                    DateUtil.formatDateTime(user.getFreezeStartTime()),
                    DateUtil.formatDateTime(user.getFreezeEndTime()));
        }

        SystemUserVO userVo = SystemUserVO.convert(user);
        // 登录
        StpUtil.login(user.getId());
        // token信息
        SaTokenInfo token = StpUtil.getTokenInfo();
        // 将用户信息存储到sa-session中
        StpUtil.getSession().set(SystemConst.SA_TOKEN_SESSION_USER_INFO_KEY, userVo);

        return UserTokenVO.create(token.getTokenName(), token.getTokenValue(), userVo);
    }

    /**
     * 比较密码是否一致
     *
     * @param password1 加密后的密码
     * @param password2 明文密码
     * @return 比对结果，true：密码一致，false：密码不一致
     */
    private boolean comparePassword(String password1, String password2) {
        return password1.equals(userService.encryptPassword(password2));
    }
}
